package com.cloud.tool.properties;

import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author WangZY
 * @classname PropertiesLoaderRewrite
 * @date 2022/7/29 17:48
 * @description spring默认的PropertiesPropertySourceLoader采用ISO_8859_1编码读取，这里修改为UTF-8防止中文乱码
 */
@Order(value = Ordered.HIGHEST_PRECEDENCE + 100)
public class RewritePropertiesPropertySourceLoader extends PropertiesPropertySourceLoader {
    private static final String XML_FILE_EXTENSION = ".xml";

    @Override
    public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
        Map<String, ?> properties = loadProperties(resource);
        if (properties.isEmpty()) {
            return Collections.emptyList();
        }
        return Collections.singletonList(new OriginTrackedMapPropertySource(name, properties));
    }

    private Map<String, ?> loadProperties(Resource resource) throws IOException {
        String filename = resource.getFilename();
        if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
            return (Map) PropertiesLoaderUtils.loadProperties(resource);
        }
        return new RewriteOriginTrackedPropertiesLoader(resource).load();
    }
}